<template>
	<view class="container">
		<u-loading-page bg-color="rgba(0, 0, 0, 0.8)" :loading-text="loadingText" :loading="loading"
			style="z-index: 99;" loading-mode="spinner" loading-color="#409EFF" color="#409EFF"
			font-size="15"></u-loading-page>
		<div class="card-style" style="width: 97%; margin: 0 auto;">
			<div class="tips">
				<image src="/static/icon/allFundus.png" alt="" class="tips-icon"></image>
				<text class="tips-text">上传全部眼底图像</text>
			</div>
			<u-upload class="file-upload" :fileList="fileList" @afterRead="afterRead" multiple :maxCount="11"
				:previewImage="false">
				<div class="file-upload-inner">
					<image src="/static/image/upload.png" style="width: 50px;height: 50px;"></image>
					<div class="file-upload-text"><u--text type="primary" text="点击图标"></u--text>上传左右眼底图像</div>
				</div>
			</u-upload>
		</div>
		<div class="file-area card-style">
			<div class="tips">
				<image src="/static/icon/pair.png" alt="" class="tips-icon" style="width: 25px;height: 25px"></image>
				<text class="tips-text">为眼底图像配对</text>
			</div>
			<div class="single-file" v-for="(item,index) in uploadFile" :key="index">
				<div class="image-preview">
					<image :src="item.url" alt="" style="width: 100%;height: 100%"></image>
				</div>
				<div class="middle-blank"></div>
				<div class="select-direction-and-pair">
					<u-radio-group v-model="item.direction" placement="column">
						<u-radio label="左眼眼底" name="左眼眼底">
						</u-radio>
						<u-radio :customStyle="{marginTop: '5px'}" label="右眼眼底" name="右眼眼底">
						</u-radio>
					</u-radio-group>
					<div>
						<u--text :line="1" text="暂未配对，点击配对" v-if="item.pair === ''" @click="startManualPair(index)"
							type="error" size="14" :bold="true"></u--text>
						<u--text :line="1" :text="'已与' + item.pair + '配对'" v-else type="success" size="14" :bold="true"
							@click="startManualPair(index)"></u--text>
					</div>
				</div>
				<div class="right-blank"></div>
			</div>
			<div class="submit-btn">
				<u-button type="success" text="批量诊断" style="width: 30%;" size="small"
					@click="batchDiagnosis"></u-button>
				<u-button type="error" text="重置" style="width: 30%;" size="small" @click="reset"></u-button>
			</div>
		</div>
		<div class="result-area card-style">
			<div class="tips">
				<image src="/static/icon/result.png" alt="" class="tips-icon" style="width: 35px;height: 35px"></image>
				<text class="tips-text">批量预测结果及就诊建议</text>
			</div>
			<u-collapse>
				<u-collapse-item v-for="(item,index) in resultList" :key="index" :name="item.title">
					<text slot="title" class="result-title">{{item.title}}</text>
					<rich-text :nodes="item.content"></rich-text>
				</u-collapse-item>
			</u-collapse>
		</div>
		<u-toast ref="uToast"></u-toast>
		<u-picker :show="showPicker" :columns="columns" :closeOnClickOverlay="true" @close="showPicker = false"
			@cancel="showPicker = false" @confirm="confirmPicker"></u-picker>
	</view>
</template>

<script>
	import io from '@hyoga/uni-socket.io';
	import {
		batchDignosis
	} from '../../../api/dignosis'
	export default {
		data() {
			return {
				socket: null,
				loading: false,
				loadingText: "",
				// 是否显示选择配对文件的弹窗
				showPicker: false,
				columns: [],
				// 当前选择的item的下标
				nowItemIndex: null,
				// 是否使用展示用的内容
				useInitExample: 0,
				fileList: [],
				// 可视化用户上传文件
				uploadFile: [{
					url: 'https://service-plat.oss-cn-beijing.aliyuncs.com/11_right.jpg',
					filename: 'left_example',
					pair: '',
					direction: ''
				}, {
					url: 'https://service-plat.oss-cn-beijing.aliyuncs.com/11_left.jpg',
					filename: 'right_example',
					pair: '',
					direction: ''
				}],
				resultList: [{
					title: 'left_example | right_exmaple',
					content: "预测结果及就诊建议"
				}],
				form: {
					leftFilename: [],
					rightFilename: []
				},
				indexToDisease: {
					1: '糖尿病',
					2: '青光眼',
					3: '白内障',
					4: 'AMD',
					5: '高血压',
					6: '近视',
					7: '其他疾病/异常'
				},
				indexToSoultion: {
					1: '糖尿病患者应该早期进行眼底检查，并通过对糖尿病患者及其家属的健康教育，使其能够掌握DR危险因素相关知识，鼓励患者坚持健康的生活方式，遵循有效的随访计划，进而达到DR早防、早治的目的。',
					2: '青光眼是终身性疾病，虽然不能根治，但可以被控制。只有早期诊断与及时治疗，才能保持终生有用视力。大量临床实践也证明，积极的早期发现和早期干预，可以有效控制青光眼病情进展，保障患者健康的视力和生活质量。',
					3: '白内障病人可以通过裂隙灯检查、检眼镜检查、眼底照相、OCT扫描和视野检查来进行眼底检查。由于白内障可能影响眼底的评估结果，建议在专业的眼科医生指导下进行检查和诊断。',
					4: 'AMD患者应前往眼科就诊,记录症状出现的时间、严重程度、视物变形或中心暗点的范围等。同时，梳理个人及家族病史，包括是否有AMD家族史、是否患有高血压、糖尿病等全身疾病，以及个人的吸烟、饮酒史。注意是否有视力下降、视物变形、视野中心暗点、闪光感、暗适应差等症状。',
					5: '患者最好每隔3-6个月检查一次眼底。 出现急性症状及时就诊。 高血压患者如果出现血压急剧升高、视物不清、短时间内视力下降明显，甚至有恶心、呕吐等颅内压升高的症状，我们称之为高血压急症，一定要尽早就诊，做眼底镜及眼底照相等检查，明确诊断。',
					6: '建议高度近视等眼底病变高发人群每半年至一年检查一次眼底。',
					7: '建议下线就医'
				},
			}
		},
		onHide() {
			// 离开时断开Socketio连接
			if (this.socket !== null) {
				this.socket.disconnect();
			}
		},
		methods: {
			confirmPicker(obj) {
				// 修改被选择的item的pair
				for (let i = 0; i < this.uploadFile.length; i++)
					if (this.uploadFile[i].filename === obj.value[0]) {
						// 如果已经配对了 要把已经配好的另一个解除
						if (this.uploadFile[i].pair !== '') {
							for (let j = 0; j < this.uploadFile.length; j++) {
								if (this.uploadFile[j].filename === this.uploadFile[i].pair) {
									this.uploadFile[j].pair = '';
									break;
								}
							}
						}
						this.uploadFile[i].pair = this.uploadFile[this.nowItemIndex].filename
						break;
					}
				// 修改当前选择的item的pair
				this.uploadFile[this.nowItemIndex].pair = obj.value[0];

				this.showPicker = false;
			},
			startManualPair(index) {
				this.columns = []
				let array = []
				for (let i = 0; i < this.uploadFile.length; i++) {
					if (i === index) {
						continue;
					} else {
						array.push(this.uploadFile[i].filename);
					}
				}
				this.columns.push(array)
				this.nowItemIndex = index;
				this.showPicker = true;
			},
			// 重置按钮触发的函数
			reset() {
				this.form = {
					leftFilename: [],
					rightFilename: []
				}
				this.content = '预测结果及建议'
				this.resultList = [{
					title: 'left_example | right_exmaple'
				}]
				this.uploadFile = [{
					url: 'https://service-plat.oss-cn-beijing.aliyuncs.com/11_right.jpg',
					filename: 'left_example',
					pair: '',
					direction: ''
				}, {
					url: 'https://service-plat.oss-cn-beijing.aliyuncs.com/11_left.jpg',
					filename: 'right_example',
					pair: '',
					direction: ''
				}]
				this.fileList = []
				this.useInitExample = 0
				this.useInitResult = 0
			},
			// 上传图片后调用的函数
			async afterRead(event) {
				if (this.useInitExample === 0) {
					this.useInitExample = 1;
					this.uploadFile = []
				}

				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				for (let i = 0; i < lists.length; i++) {
					// 最多只能上传10个文件
					if (this.fileList.length >= 10) {
						this.$refs.uToast.show({
							type: 'warning',
							message: "最多只能上传10张图片",
							position: "top"
						});
						return;
					}
					let filename = '';
					if (lists[i].name === "" || lists[i].name === undefined) {
						filename = "image_" + this.fileList.length + ".jpg";
					} else {
						filename = lists[i].name;
					}
					this.fileList.push(lists[i])
					this.uploadFile.push({
						url: lists[i].url,
						filename: filename,
						pair: '',
						direction: ''
					})
				}

				// 将这些文件上传
				for (let i = 0; i < this.uploadFile.length; i++) {
					uni.uploadFile({
						url: `https://yiyuy.mynatapp.cc/model/uniappUploadBatchImage?filename=${this.uploadFile[i].filename}`,
						filePath: this.uploadFile[i].url,
						name: "file",
						success: (response) => {
							if (response.statusCode !== 200) {
								this.$refs.uToast.show({
									type: 'error',
									message: "请求失败",
									position: "top"
								});
							}
						}
					})

					// 同时上传到autodl
					uni.uploadFile({
						url: `http://yiyuy.nat300.top/uniappUploadImage?filename=${this.uploadFile[i].filename}`,
						filePath: this.uploadFile[i].url,
						name: "file",
						success: (response) => {
							if (response.statusCode !== 200) {
								this.$refs.uToast.show({
									type: 'error',
									message: "请求失败",
									position: "top"
								});
							}
						}
					})
				}
			},
			// 开始批量诊断
			async batchDiagnosis() {
				// 做一些判断
				let left = 0,
					right = 0;
				for (let i = 0; i < this.uploadFile.length; i++) {
					if (this.uploadFile[i].direction === '') {
						this.$refs.uToast.show({
							type: 'warning',
							message: "文件" + this.uploadFile[i].filename + "尚未选择眼底类型",
							position: "top"
						});
						return;
					}

					if (this.uploadFile[i].direction === '左眼眼底') left++
					else right++

					if (this.uploadFile[i].pair === '') {
						this.$refs.uToast.show({
							type: 'warning',
							message: "文件" + this.uploadFile[i].filename + "暂未配对",
							position: "top"
						});
						return;
					}
				}

				// 左右眼底数量是否相等
				if (left != right) {
					this.$refs.uToast.show({
						type: 'warning',
						message: "左右眼底数量不相等，请重新选择眼底类型",
						position: "top"
					});
				}

				// 配对
				for (let i = 0; i < this.uploadFile.length; i++) {
					if (this.uploadFile[i].direction === '左眼眼底') {
						this.form.leftFilename.push(this.uploadFile[i].filename)
						this.form.rightFilename.push(this.uploadFile[i].pair)
					}
				}

				this.loading = true
				this.loadingText = '开始批量诊断...'
				
				this.resultList = []
				
				this.socket = io('https://yiyuy.mynatapp.cc/model', {
					transports: ['websocket'],
				});
				
				// 连接成功后 开始正式显示内容
				this.socket.on('connect', () => {
					this.loadingText = 'LLAVA,亮度增强网络与多模态网络正在努力工作...'
				});
				
				// 监听服务器事件
				this.socket.on('uniapp_batch_diagnosis_response', (data) => {
					// 收到服务器推送的消息，可以跟进自身业务进行操作
					let threshold = 0.5
					if (data === '[OVER]') {
						this.loading = false;
						
						this.$refs.uToast.show({
							type: 'success',
							message: "批量诊断成功！",
							position: "top"
						});
						
						// 重置表单
						this.form = {
							leftFilename: [],
							rightFilename: [],
						}
						
						this.socket.disconnect()
					} else {
						let obj = {
							"title": data.leftFilename + " | " + data
								.rightFilename,
							"content": ""
						}
						
						let array = []
						let sum = 0
						for (let j = 0; j < data.prob.length; j++) {
							if (data.prob[j] >= threshold) {
								array.push(1)
								sum++
							} else {
								array.push(0)
							}
						}
						
						if (sum === 1 && array[0] === 1) {
							obj.content = "诊断情况: 正常"
						} else {
							// 完成诊断情况内容
							obj.content = "<h4>诊断情况: </h4>"
							for (let j = 0; j < array.length; j++) {
								if (array[j] === 1) {
									obj.content += this.indexToDisease[j] + " "
								}
							}
							// 构建就诊建议
							obj.content += "<h4>就诊建议: </h4>"
							for (let j = 0; j < array.length; j++) {
								if (array[j] === 1) {
									obj.content += "<h5>" + this.indexToDisease[j] + "</h5>"
									obj.content += this.indexToSoultion[j]
								}
							}
						}
						
						this.resultList.push(obj)
					}
				});
				
				this.socket.emit('uniappStartBatchDiagnosis',{leftFilename: this.form.leftFilename, rightFilename: this.form.rightFilename})
			}
		}
	}
</script>

<style>
	@keyframes moveIn {
		0% {
			opacity: 0;
			transform: translateY(12px);
		}

		100% {
			opacity: 1;
			transform: translateY(0);
		}
	}

	.container {
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
	}

	.card-style {
		border-radius: 4px;
		border: 1px solid #ebeef5;
		background-color: #fff;
		overflow: hidden;
		color: #303133;
		transition: .3s;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
		animation: moveIn .3s cubic-bezier(.4, 0, .2, 1) forwards;
	}

	.tips {
		display: flex;
		align-items: center;
	}

	.tips-icon {
		width: 30px;
		height: 30px;
	}

	.tips-text {
		font-size: 14px;
		font-weight: bold;
	}

	.file-upload {
		width: 95%;
		border: 1px dashed black;
		display: flex;
		align-items: center;
		margin: 0 auto;
		margin-bottom: 10px;
	}

	.file-upload-inner {
		width: 700rpx;
		height: 100%;
		display: flex;
		align-items: center;
		flex-direction: column;
		justify-content: center;
	}

	.file-upload-text {
		display: flex;
		font-size: 15px;
	}

	.file-area {
		width: 95%;
		margin: 5px auto;
		padding: 5px;
		height: 40%;
		background-color: #fff;
	}

	.single-file {
		display: flex;
		margin-top: 5px;
		border-bottom: 1px solid #e5e5e5;
	}

	.image-preview {
		height: 50px;
		width: 55px;
	}

	.filename {
		font-size: 17px;
		font-weight: bold;
	}
	
	.middle-blank,.right-blank {
		width: 20px;
	}

	.select-direction-and-pair {
		flex: 1;
		display: flex;
		align-items: center;
	}

	.submit-btn {
		margin-top: 10px;
		display: flex;
	}

	.result-area {
		width: 97%;
		margin: 4px auto;
		flex: 1;
	}

	.result-title {
		font-weight: bold;
	}

	.popup-box {
		height: 300px;
		overflow-y: scroll;
	}
</style>